package smecta.client.print.controller.product;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.converter.DefaultStringConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import smecta.client.print.domain.ScpPackage;
import smecta.client.print.domain.ScpProduct;
import smecta.client.print.domain.ScpProductPropertyValuelist;
import smecta.client.print.domain.ScpProductSpecs;
import smecta.client.print.mapper.ScpPackageMapper;
import smecta.client.print.mapper.ScpProductMapper;
import smecta.client.print.mapper.ScpProductPropertyValuelistMapper;
import smecta.client.print.mapper.ScpProductSpecsMapper;
import smecta.client.print.util.CustomTextFieldTableCell;

import java.util.HashMap;
import java.util.List;

@Component
public class PackageController {

    @Autowired
    private ScpProductPropertyValuelistMapper scpProductPropertyValuelistMapper;

    @Autowired
    private ScpPackageMapper scpPackageMapper;

    @Autowired
    private ScpProductMapper scpProductMapper;

    @Autowired
    private ScpProductSpecsMapper scpProductSpecsMapper;

    @FXML
    private TableView<ScpPackage> table;

    @FXML
    private TableColumn<ScpPackage, String> col0;

    @FXML
    private TableColumn<ScpPackage, String> col1;

    @FXML
    private TableColumn<ScpPackage, String> col2;

    @FXML
    private TableColumn<ScpPackage, String> col3;

    @FXML
    private TableColumn<ScpPackage, String> col4;

    @FXML
    private TableColumn<ScpPackage, String> col5;

    @FXML
    private TableColumn<ScpPackage, String> col6;

    @FXML
    private TableColumn<ScpPackage, String> col7;

    @FXML
    private TableColumn<ScpPackage, String> col8;

    @FXML
    private TableColumn<ScpPackage, String> col9;

    public void manualInit() {
        // 初始化数据
        List<ScpPackage> list = scpPackageMapper.selectAll();
        // 可以添加更多数据...
        table.getItems().clear();
        table.getItems().addAll(list);
    }

    // 属性 枚举值
    private HashMap<String, ObservableList<String>> attrEnumMap = new HashMap<>();

    @FXML
    public void initialize() {
        initColumnEnum();
        table.setEditable(true); // 使表格可编辑

        col0.setCellValueFactory(new PropertyValueFactory<>("productId"));
        col0.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("productId")));
        col0.setOnEditCommit(
                event -> {
                    event.getTableView().getItems().get(
                            event.getTablePosition().getRow()).setProductId(Long.valueOf(event.getNewValue()));
                    updateCol2Col3DependOnCol1(event.getRowValue());
                }
        );

        col1.setCellValueFactory(new PropertyValueFactory<>("pinming"));

        col2.setCellValueFactory(new PropertyValueFactory<>("guige"));

        col3.setCellValueFactory(new PropertyValueFactory<>("seze"));

        col4.setCellValueFactory(new PropertyValueFactory<>("pihao"));
        col4.setCellFactory((col -> new CustomTextFieldTableCell<>(new DefaultStringConverter())));
        col4.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setPihao(event.getNewValue())
        );

        col5.setCellValueFactory(new PropertyValueFactory<>("jitaihao"));
        col5.setCellFactory((col -> new CustomTextFieldTableCell<>(new DefaultStringConverter())));
        col5.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setJitaihao(event.getNewValue())
        );

        col6.setCellValueFactory(new PropertyValueFactory<>("guanse"));
        col6.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("guanse")));
        col6.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setGuanse(event.getNewValue())
        );

        col7.setCellValueFactory(new PropertyValueFactory<>("tongzhong"));
        col7.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("tongzhong")));
        col7.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setTongzhong(event.getNewValue())
        );

        col8.setCellValueFactory(new PropertyValueFactory<>("xiangzhong"));
        col8.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("xiangzhong")));
        col8.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setXiangzhong(event.getNewValue())
        );

        col9.setCellValueFactory(new PropertyValueFactory<>("tingyong"));
        col9.setCellFactory(ComboBoxTableCell.forTableColumn(attrEnumMap.get("tingyong")));
        col9.setOnEditCommit(
                event -> event.getTableView().getItems().get(
                        event.getTablePosition().getRow()).setTingyong(event.getNewValue())
        );
    }

    private void updateCol2Col3DependOnCol1(ScpPackage productSpecs) {
        if (productSpecs == null) {
            return;
        }
        ScpProduct product = scpProductMapper.selectByPrimaryKey(productSpecs.getProductId());
        if (ObjectUtils.isEmpty(product)) {
            return;
        }

        // 刷新表格对应的行，以显示更新后的值
        int rowIndex = table.getItems().indexOf(productSpecs);
        if (rowIndex != -1) {
            table.refresh();
            table.getItems().get(rowIndex).setPinming(product.getPinming());
            table.getItems().get(rowIndex).setGuige(product.getGuige());
            table.getItems().get(rowIndex).setSeze(product.getSeze());
        }
    }

    private void initColumnEnum() {
        attrEnumMap.clear();
        List<ScpProductPropertyValuelist> all = scpProductPropertyValuelistMapper.selectScpProductPropertyValuelistList(new ScpProductPropertyValuelist());
        for (ScpProductPropertyValuelist item : all) {
            String key = item.getCode();
            String value = item.getValue();
            if (!attrEnumMap.containsKey(key)) {
                attrEnumMap.put(key, FXCollections.observableArrayList());
            }
            attrEnumMap.get(key).add(value);
        }

        List<ScpProductSpecs> specs = scpProductSpecsMapper.selectAll();
        for (ScpProductSpecs item : specs) {
            String key = "guige";
            String value = item.getGuige();
            if (!attrEnumMap.containsKey(key)) {
                attrEnumMap.put(key, FXCollections.observableArrayList());
            }
            attrEnumMap.get(key).add(value);
        }

        List<ScpProduct> products = scpProductMapper.selectAll();
        for (ScpProduct item : products) {
            String key = "productId";
            if (!attrEnumMap.containsKey(key)) {
                attrEnumMap.put(key, FXCollections.observableArrayList());
            }
            attrEnumMap.get(key).add(item.getId().toString());
        }

        String key = "tingyong";
        if (!attrEnumMap.containsKey(key)) {
            attrEnumMap.put(key, FXCollections.observableArrayList());
        }
        attrEnumMap.get(key).add("是");
        attrEnumMap.get(key).add("否");
    }

    public void add() {
        table.getItems().add(new ScpPackage(null,null,null,null,"请输入","请输入","请选择","请选择","请选择","请选择"));
        table.refresh(); // 刷新表格显示新数据
    }

    public void del() {
        table.getItems().remove(table.getItems().size() - 1);
        table.refresh(); // 刷新表格显示新数据
    }

    public void save() {
        List<ScpPackage> all = scpPackageMapper.selectAll();
        for (int i = 0; i < all.size(); i++) {
            scpPackageMapper.deleteByPrimaryKey(all.get(i).getId());
        }

        table.getItems().forEach(item -> {
            List<ScpPackage> query = scpPackageMapper.select(item);
            if (CollectionUtils.isEmpty(query)) {
                scpPackageMapper.insertSelective(item);
            }
        });
    }
}